import { ChangeDetectionStrategy, Component, Injector, OnInit } from '@angular/core';
import { STColumn } from '@delon/abc/st';
import { SFSchema } from '@delon/form';
import { UrlOfSystemTable } from '@routes/system/_base';
import { SystemDictService } from '@routes/system/dict/dict.service';
import { RoleVO } from '@types';

import { SystemRoleDataScopeComponent } from '../data-scope/data-scope.component';
import { SystemEditRoleComponent } from '../edit-role/edit-role.component';
import { SystemRoleUserComponent } from '../role-user/role-user.component';
import { SystemRoleService } from '../role.service';

@Component({
    selector: 'app-system-role-list',
    templateUrl: './role-list.component.html',
    styleUrls: ['./role-list.component.less'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class SystemRoleListComponent extends UrlOfSystemTable implements OnInit {
    columns: STColumn[] = [
        {
            title: '编号',
            fixed: 'left',
            width: '50px',
            type: 'checkbox',
            className: 'text-center',
            exported: false
        },
        {
            title: '角色编号',
            index: 'roleId',
            className: 'text-center',
            width: '130px',
            type: 'widget',
            widget: { type: 'long-text', params: ({ record }) => ({ text: record.roleId }) }
        },
        {
            title: '角色名称',
            index: 'roleName',
            className: 'text-center',
            width: '130px',
            type: 'widget',
            widget: { type: 'long-text', params: ({ record }) => ({ text: record.roleName }) }
        },
        {
            title: '权限字符',
            index: 'roleKey',
            className: 'text-center',
            width: '130px',
            type: 'widget',
            widget: { type: 'long-text', params: ({ record }) => ({ text: record.roleKey }) }
        },
        {
            title: '显示顺序',
            index: 'roleSort',
            className: 'text-center',
            width: '130px',
            type: 'widget',
            widget: { type: 'long-text', params: ({ record }) => ({ text: record.roleSort }) }
        },
        {
            title: '状态',
            index: 'status',
            className: 'text-center',
            width: '130px',
            render: 'statusCustom'
        },
        {
            title: '创建时间',
            index: 'createTime',
            className: 'text-center',
            width: '200px',
            type: 'widget',
            widget: { type: 'long-text', params: ({ record }) => ({ text: record.createTime }) }
        },
        {
            title: '操作',
            className: 'text-center',
            buttons: [
                {
                    // text: '修改',
                    iif: item => item.roleId !== 1,
                    tooltip: `修改`,
                    acl: ['admin', 'system:role:edit'],
                    icon: 'edit',
                    click: item => this.editRole(item)
                },
                {
                    // text: '删除',
                    iif: item => item.roleId !== 1,
                    tooltip: '删除',
                    acl: ['admin', 'system:role:remove'],
                    icon: 'delete',
                    className: 'text-error',
                    click: item => this.delRole(item)
                },
                {
                    // text: '删除',
                    iif: item => item.roleId !== 1,
                    tooltip: '数据权限',
                    acl: ['admin', 'system:role:edit'],
                    icon: 'down-circle',
                    click: item => this.dataScope(item)
                },
                {
                    // text: '删除',
                    iif: item => item.roleId !== 1,
                    tooltip: '分配用户',
                    acl: ['admin', 'system:role:edit'],
                    icon: 'user',
                    click: item => this.authUser(item)
                }
            ]
        }
    ];
    searchSchema: SFSchema = {
        properties: {
            roleName: {
                title: '角色名称',
                type: 'string',
                ui: {
                    placeholder: '请输入角色名称'
                }
            },
            roleKey: {
                title: '权限字符',
                type: 'string',
                ui: {
                    placeholder: '请输入权限字符'
                }
            },
            status: {
                title: '状态',
                type: 'string',
                ui: {
                    placeholder: '角色状态',
                    widget: 'select',
                    asyncData: () => this.injector.get(SystemDictService).getDicts('sys_normal_disable')
                }
            },
            range: {
                type: 'string',
                title: '创建时间',
                ui: {
                    widget: 'date',
                    mode: 'range',
                    placeholder: '选择时间段'
                }
            }
        }
    };
    url: string = this.apiUrl.role.list;

    constructor(
        protected override injector: Injector,
        protected roleSrv: SystemRoleService
    ) {
        super(injector);
    }

    getPopConfirmText(item: any) {
        let text = item.status === '0' ? '停用' : '启用';
        return `确认要"${text}""${item.roleName}"角色吗?`;
    }

    /**
     * 更改状态确认
     * @param item
     * @param index
     */
    confirmStatus(item: any, index: number) {
        const text = item.status === '0' ? '停用' : '启用';
        const _status = item.status === '0' ? '1' : '0';
        this.roleSrv.changeRoleStatus({ roleId: item.roleId, status: _status }).subscribe(res => {
            this.msg.success(`${text}成功`);
            this.st.setRow(index, { status: _status }, { refreshSchema: true });
        });
    }

    /**
     * 更改状态取消
     * @param item
     * @param index
     */
    cancelStatus(item: any, index: number) {
        this.st.setRow(index, { status: item.status }, { refreshSchema: true });
    }

    addRole() {
        this.modal
            .creatStaticModal(SystemEditRoleComponent, { item: {} }, 'md', {
                nzTitle: '添加角色'
            })
            .subscribe(res => {
                if (res) {
                    this.st.reset();
                }
            });
    }

    editRole(item: RoleVO) {
        this.modal
            .creatStaticModal(SystemEditRoleComponent, { item, type: 'edit' }, 'md', {
                nzTitle: `修改角色【${item.roleName}】`
            })
            .subscribe(res => {
                if (res) {
                    this.st.reset();
                }
            });
    }

    delRole(item: RoleVO) {
        this.modalSrv.confirm({
            nzTitle: '删除提示',
            nzContent: `确认删除角色为 ${item.roleName} 的数据项？`,
            nzOnOk: () =>
                this.roleSrv.delRoles(item.roleId.toString()).subscribe(res => {
                    if (res.isComplete) {
                        this.msg.success('删除成功');
                    }
                    this.st.reload();
                })
        });
    }

    dataScope(item: RoleVO) {
        this.modal
            .creatStaticModal(SystemRoleDataScopeComponent, { item }, 'md', {
                nzTitle: `分配角色【${item.roleName}】数据权限`
            })
            .subscribe(res => {});
    }

    authUser(item: RoleVO) {
        this.modal
            .creatStaticModal(SystemRoleUserComponent, { item }, 'lg', {
                nzTitle: `角色【${item.roleName}】成员`
            })
            .subscribe(res => {});
    }

    delRoleS(items: RoleVO[]) {
        this.modalSrv.confirm({
            nzTitle: '删除提示',
            nzContent: `确认删除角色为 ${items.map(xx => xx.roleName).join(',')} 的数据项？`,
            nzOnOk: () =>
                this.roleSrv.delRoles(items.map(xx => xx.roleId).join(',')).subscribe(res => {
                    if (res.isComplete) {
                        this.msg.success('删除成功');
                    }
                    this.st.reload();
                })
        });
    }
}
